/*
 * This file is part of TradeHelper library.
 *
 * TradeHelper library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TradeHelper library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TradeHelper library.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.rag.forum.ui;

import com.alee.extended.image.WebDecoratedImage;
import com.alee.extended.label.WebLinkLabel;
import com.alee.extended.label.WebMultiLineLabel;
import com.alee.extended.layout.VerticalFlowLayout;
import com.alee.extended.panel.GroupPanel;
import com.alee.extended.panel.WebOverlay;
import com.alee.laf.button.WebButton;
import com.alee.laf.label.WebLabel;
import com.alee.laf.menu.MenuUtils;
import com.alee.laf.menu.WebMenuItem;
import com.alee.laf.menu.WebPopupMenu;
import com.alee.laf.panel.WebPanel;
import com.alee.laf.scroll.WebScrollPane;
import com.alee.laf.separator.WebSeparator;
import com.alee.managers.hotkey.Hotkey;
import com.alee.managers.hotkey.HotkeyInfo;
import com.alee.managers.hotkey.HotkeyManager;
import com.alee.managers.hotkey.HotkeyRunnable;
import com.alee.managers.popup.PopupListener;
import com.alee.managers.popup.PopupManager;
import com.alee.managers.popup.PopupStyle;
import com.alee.managers.popup.WebPopup;
import com.alee.utils.HtmlUtils;
import com.alee.utils.SwingUtils;
import com.alee.utils.swing.PointProvider;
import com.rag.core.ForumType;
import com.rag.core.FullTopicData;
import com.rag.core.PostData;
import com.rag.forum.pages.TopicContentPanel;
import com.rag.utils.RagUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

/**
 * User: mgarin Date: 09.06.12 Time: 19:01
 */

public class TopicPopup extends WebPopup
{
    private static ImageIcon hideIcon =
            new ImageIcon ( TopicPopup.class.getResource ( "icons/topic/hide.png" ) );
    private static ImageIcon byIdIcon =
            new ImageIcon ( TopicPopup.class.getResource ( "icons/topic/by_id.png" ) );
    private static ImageIcon byTextIcon =
            new ImageIcon ( TopicPopup.class.getResource ( "icons/topic/by_text.png" ) );
    private static ImageIcon byUserIcon =
            new ImageIcon ( TopicPopup.class.getResource ( "icons/topic/by_user.png" ) );

    private static ImageIcon collapseIcon =
            new ImageIcon ( TopicPopup.class.getResource ( "icons/topic/collapse.png" ) );
    private static ImageIcon expandIcon =
            new ImageIcon ( TopicPopup.class.getResource ( "icons/topic/expand.png" ) );
    private static ImageIcon disabledIcon =
            new ImageIcon ( TopicPopup.class.getResource ( "icons/topic/disabled.png" ) );

    private HotkeyInfo escapeHotkey;

    public TopicPopup ( FullTopicData topic )
    {
        super ( PopupManager.getPopupPainter ( PopupStyle.bordered ) );
        setMargin ( 0 );

        add ( createTopicDescription ( topic ) );

        // Для быстрого закрытия попапа по ESC
        addPopupListener ( new PopupListener ()
        {
            public void popupOpened ()
            {
                escapeHotkey = HotkeyManager
                        .registerHotkey ( TopicPopup.this, Hotkey.ESCAPE, new HotkeyRunnable ()
                        {
                            public void run ( KeyEvent e )
                            {
                                TopicPopup.this.hidePopup ();
                            }
                        } );
            }

            public void popupClosed ()
            {
                HotkeyManager.unregisterHotkey ( escapeHotkey );
                escapeHotkey = null;
            }
        } );
    }

    private WebPanel createTopicDescription ( FullTopicData topic )
    {
        WebPanel descriptionPanel = new WebPanel ();

        // Панель с итемами топика
        descriptionPanel
                .add ( new TopicContentPanel ( ForumType.topicPopup, topic.getTopicData (), null,
                        true, false, true, false ), BorderLayout.NORTH );

        // Панель с постами
        final WebPanel posts = new WebPanel ( new VerticalFlowLayout ( 0, 0 ) );

        int postNumber = 1;
        String authorId = topic.getPosts ().get ( 0 ).getUserId ();
        for ( PostData postData : topic.getPosts () )
        {
            WebPanel post = new WebPanel ( new BorderLayout ( 10, 10 ) )
            {
                public Dimension getPreferredSize ()
                {
                    Dimension ps = super.getPreferredSize ();
                    ps.width = 0;
                    return ps;
                }
            };
            post.setMargin ( 10 );

            // Подсветка фона постов автора топика
            if ( postData.getUserId ().equals ( authorId ) )
            {
                post.setBackground ( new Color ( 240, 240, 255 ) );
            }

            // Аватар

            final WebDecoratedImage avatar = new WebDecoratedImage ( postData.getAvatar () );
            avatar.setShadeWidth ( 5, false );
            avatar.setRound ( 0 );
            avatar.setVerticalAlignment ( WebDecoratedImage.TOP );
            post.add ( avatar, BorderLayout.WEST );

            // Содержимое топика

            WebLinkLabel topicAuthor = RagUtils.createUserInfo ( postData.getAuthor () );
            final WebMultiLineLabel topicText = new WebMultiLineLabel ( getPostText ( postData ) );
            topicText.putClientProperty ( GroupPanel.FILL_CELL, true );
            GroupPanel authorAlign = new GroupPanel ( SwingUtils.boldFont ( topicAuthor ) );
            GroupPanel topicContent = new GroupPanel ( 4, false, authorAlign, topicText );

            // Оверлэй тулбар

            WebLabel postNumberLabel = new WebLabel ( "#" + postNumber );

            final WebButton hidePost = WebButton.createIconWebButton ( hideIcon );
            hidePost.setDrawFocus ( false );

            final WebPopupMenu hideMenu = new WebPopupMenu ();

            WebMenuItem hideById = new WebMenuItem ( "Скрыть данный пост", byIdIcon );
            hideById.addActionListener ( new ActionListener ()
            {
                public void actionPerformed ( ActionEvent e )
                {
                    // todo
                }
            } );
            hideMenu.add ( hideById );

            hideMenu.addSeparator ();

            WebMenuItem hideByText =
                    new WebMenuItem ( "Скрыть все посты с данным текстом", byTextIcon );
            hideByText.addActionListener ( new ActionListener ()
            {
                public void actionPerformed ( ActionEvent e )
                {
                    // todo
                }
            } );
            hideMenu.add ( hideByText );

            WebMenuItem hideByAuthor =
                    new WebMenuItem ( "Скрыть все посты от этого пользователя", byUserIcon );
            hideByAuthor.addActionListener ( new ActionListener ()
            {
                public void actionPerformed ( ActionEvent e )
                {
                    // todo
                }
            } );
            hideMenu.add ( hideByAuthor );

            MenuUtils.setupPopupMenu ( hidePost, hideMenu, new PointProvider ()
            {
                public Point provide ()
                {
                    return new Point ( hidePost.getWidth () - hideMenu.getPreferredSize ().width,
                            hidePost.getHeight () + 1 );
                }
            } );

            boolean canCollapse =
                    avatar.getPreferredSize ().height < topicContent.getPreferredSize ().height;
            final WebButton collapsePost =
                    WebButton.createIconWebButton ( canCollapse ? collapseIcon : disabledIcon );
            collapsePost.setDrawFocus ( false );
            collapsePost.setEnabled ( canCollapse );
            collapsePost.addActionListener ( new ActionListener ()
            {
                boolean collapsed = false;

                public void actionPerformed ( ActionEvent e )
                {
                    collapsed = !collapsed;
                    collapsePost.setIcon ( collapsed ? expandIcon : collapseIcon );
                    topicText.setPreferredSize ( collapsed ? new Dimension ( 0, 0 ) : null );
                    topicText.revalidate ();
                }
            } );

            GroupPanel controlsPanel =
                    new GroupPanel ( 4, postNumberLabel, hidePost, collapsePost );


            // Сгрупированная панель топика
            WebOverlay overlay = new WebOverlay ( topicContent );
            overlay.addOverlay ( controlsPanel, WebOverlay.RIGHT, WebOverlay.TOP );
            overlay.setOpaque ( false );
            post.add ( overlay, BorderLayout.CENTER );

            // Добавляем пост и разделитель после, если необходимо
            posts.add ( post );
            if ( postNumber < topic.getPosts ().size () )
            {
                posts.add ( new WebSeparator ( WebSeparator.HORIZONTAL ) );
            }

            postNumber++;
        }

        WebScrollPane scrollPane = new WebScrollPane ( posts, false );
        scrollPane.setHorizontalScrollBarPolicy ( WebScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
        descriptionPanel.add ( scrollPane, BorderLayout.CENTER );

        return descriptionPanel;
    }

    private String getPostText ( PostData postData )
    {
        return HtmlUtils.getPlainText ( postData.getMessage () );
    }
}